class AccountController < ApplicationController
  layout "main"
  before_filter :login_required, :only => [ :index, :update_password, :change_email, :change_password ]

  def index
  end

  def show
    @per_page = 10
    @user = User.find_by_login(params[:id])
    @medias = Media.find(:all, :conditions => ["deleted_at is NULL and upload_complete = 1 and user_id = ?", @user.id])
    @pages, @medias = paginate(:medias, {:conditions => ["deleted_at is NULL and upload_complete = 1 and user_id = ?", @user.id], :order => 'rating desc, created_at desc', :per_page => @per_page})
  end

  def login
    if !params[:return_to].nil?
      session[:return_to] = params[:return_to]
    end
    return unless request.post?
    @login = params[:login]  #add this variable
    self.current_user = User.authenticate(params[:login], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default(:controller => '/account', :action => 'show', :id => current_user.login)
      flash[:notice] = "Logged in successfully."
    else
      flash[:error] = "Could not login."
    end
  end

  def signup
    @user = User.new(params[:user])
    return unless request.post?
    @user.save!
    redirect_to :controller => '/quote', :action => 'index'
    flash[:notice] = "Thanks for signing up!  Please check your email to activate your account. <script type='text/javascript'>urchinTracker('/goaltrack/sentemail');</script>"
  rescue ActiveRecord::RecordInvalid
    render :action => 'signup'
  end
  
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default(:controller => '/account', :action => 'index')
  end

  def activate
    flash.clear  
    return if params[:id] == nil and params[:activation_code] == nil
    activator = params[:id] || params[:activation_code]
    @user = User.find_by_activation_code(activator) 
    if @user and @user.activate
      redirect_back_or_default(:controller => '/account', :action => 'login')
      flash[:notice] = "Your account has been activated.  Please login. <script type='text/javascript'>urchinTracker('/goaltrack/activated');</script>"
    else
      flash[:error] = "Unable to activate the account.  Please check or enter manually."
    end
  end
  
  
  
  def forgot_password
    return unless request.post?
    @user = User.find_by_email(params[:email])
    if !@user.nil? and @user
      @user.forgot_password
      @user.save
      redirect_back_or_default(:controller => '/account', :action => 'index')
      flash[:notice] = "A password reset link has been sent to your email address" 
    else
      flash[:error] = "Could not find a user with that email address" 
    end
  end

  def reset_password
    @user = User.find_by_password_reset_code(params[:id])
    raise if @user.nil?
    return if @user unless params[:password]
      if (params[:password] == params[:password_confirmation])
        self.current_user = @user #for the next two lines to work
        current_user.password_confirmation = params[:password_confirmation]
        current_user.password = params[:password]
        @user.reset_password
        if current_user.save
          flash[:notice] = "Password reset"
        else
          flash[:error] = "Password not reset" 
        end
      else
        flash[:error] = "Password mismatch" 
      end  
      redirect_back_or_default(:controller => '/account', :action => 'index') 
  rescue
    logger.error "Invalid Reset Code entered" 
    flash[:error] = "Sorry - That is an invalid password reset code. Please check your code and try again. (Perhaps your email client inserted a carriage return?" 
    redirect_back_or_default(:controller => '/account', :action => 'index')
  end
  
  def update_password
    if (params[:password] == params[:password_confirmation])
      if User.authenticate(current_user.login,params[:old_password])
        current_user.password = params[:password]
        current_user.password_confirmation = params[:password_confirmation]
        begin
          current_user.save!
          flash[:notice] = 'Successfully changed your password.'
        rescue ActiveRecord::RecordInvalid => e
          flash[:error] = "Couldn't change your password: #{e}" 
        end
      else
        flash[:error] = "Couldn't change your password: is that really your current password?" 
      end
    else
      flash[:error] = "Password mismatch" 
    end

    respond_to do |format|
      format.html { redirect_to :action => "change_password" }
    end
  end
  
  def change_email
    @user = self.current_user
    return unless request.post?
    unless params[:user][:email].blank?
      @user.change_email_address(params[:user][:email])
      if @user.save
        @changed = true
      end
    else
      flash[:notice] = "Please enter an email address" 
    end
  end

  def activate_new_email
    flash.clear  
    return unless params[:id].nil? or params[:email_activation_code].nil?
    activator = params[:id] || params[:email_activation_code]
    @user = User.find_by_email_activation_code(activator) 
    if @user and @user.activate_new_email
      redirect_back_or_default(:controller => '/account', :action => 'index')
      flash[:notice] = "The email address for your account has been updated." 
    else
      flash[:error] = "Unable to update the email address." 
    end
  end
end
